<template>
  <div style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;">
    <div style="width: 360px;padding: 24px;box-shadow: 0 4px 10px rgba(0,0,0,0.2);border-radius: 8px;">
      <flex-box style="width: 100%;" gap="12px" flex-direction="column" align-items="flex-start">
        <div style="font-size: 20px;">
          AI Examiner
        </div>
        <el-input id="login_username" @keydown="(e) => {
          if (e.code == 'Enter' || e.code == 'NumpadEnter') {
            tool.document.getElementById('login_password').focus();
          }
        }" size="medium" v-model="username" placeholder="用户名"></el-input>
        <el-input id="login_password" @keydown="(e) => {
          if (e.code == 'Enter' || e.code == 'NumpadEnter') {
            handleLogin()
          }
        }" size="medium" v-model="password" placeholder="密码" type="password"></el-input>
        <div v-if="error.length" style="width: 100%;font-size: 14px;color: red;text-align: left;">
          {{ error }}
        </div>
        <div style="width: 100%;text-align: right;">
          <el-button @click="handleLogin" type="primary">登录</el-button>
        </div>
      </flex-box>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import tool from '../modules/tool'
import { useStore } from '../modules/store'
const store = useStore()
import router from '../modules/router'
import flexBox from '../components/flexBox.vue';

const username = ref('')
const password = ref('')
const error = ref('')

const handleClearError = () => {
  error.value = ''
}

watch(() => username.value, handleClearError)
watch(() => password.value, handleClearError)

const handleLogin = async () => {
  handleClearError()
  await tool.flow(async () => {
    if (username.value == '') throw '请输入用户名'
    if (password.value == '') throw '请输入密码'
    let re = await tool.requestData('/user/adminLogin', {}, {
      username: username.value,
      password: password.value
    }, 'post')
    if (re.status) {
      store.updateUserData(re.data)
      tool.event.setItem('token', re.data.token)
      router.push('/')

      if (!localStorage.getItem('userData')) store.showModal2('提示', '是否保存登录信息，下次打开此站点时自动登录？', () => {
        localStorage.setItem('userData', JSON.stringify({
          username: username.value,
          password: password.value
        }))
      }, true, () => store.hideModal2())
    } else {
      throw re.content
    }
  }, (err) => {
    localStorage.removeItem('userData')
    tool.toast.error(`${err}`)
  })
}

onMounted(async () => {
  await tool.wait(0.1)
  tool.document.getElementById('login_username').focus();

  if (localStorage.getItem('userData')) {
    let data = JSON.parse(localStorage.getItem('userData'))
    username.value = data.username
    password.value = data.password
    await handleLogin()
  }
})
</script>

<style scoped></style>